package mspbots.autotask.data.core.users;


import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.autotask.common.ResultMsg;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * mspbots.core.sync.autotask.receivers.AutoTaskUserReceiver
 *
 * @author <a href="https://github.com/vnobo">Alex bob</a>
 * @date Created by 2020/7/10
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class UsersReceiver {

    private final UsersRepository usersRepository;

    @RabbitListener(queues = "auto-task.users.sync")
    public void processMessage(ResultMsg content) {

        Users users = Users.builder().otherId(content.getId()).tenantId(content.getTenantId())
                .syncTime(content.getSyncDate())
                .createdTime(LocalDateTime.now())
                .updatedTime(LocalDateTime.parse(content.getEntity().get("hireDate").textValue(),
                        DateTimeFormatter.ISO_DATE_TIME))
                .entity(content.getEntity())
                .build();

        this.usersRepository.findByOtherIdAndTenantId(content.getId(), content.getTenantId())
                .map(ticket -> {
                    users.setId(ticket.getId());
                    return users;
                })
                .defaultIfEmpty(users)
                .flatMap(this.usersRepository::save).block(Duration.ofSeconds(10));
    }

}
